package com.retail.marketing.server.controller;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Period;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.retail.common.log.annotation.Log;
import com.retail.common.log.enums.BusinessType;
import com.retail.common.security.annotation.RequiresPermissions;
import com.retail.marketing.common.domain.TCoupon;
import com.retail.marketing.server.service.ITCouponService;
import com.retail.common.core.web.controller.BaseController;
import com.retail.common.core.domain.Result;
import com.retail.common.core.utils.poi.ExcelUtil;
import com.retail.common.core.web.page.TableDataInfo;

/**
 * 优惠券管理Controller
 *
 * @author retail
 * @date 2024-02-27
 */
@RestController
@RequestMapping("/coupon")
public class TCouponController extends BaseController
{
    @Autowired
    private ITCouponService tCouponService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final String redisKey="MARKETING:COUPON";
    /**
     * 查询优惠券管理列表
     */
    @RequiresPermissions("marketing:coupon:list")
    @GetMapping("/list")
    public TableDataInfo list(TCoupon tCoupon)
    {
        startPage();
        BoundHashOperations<String,Object,Object> couponMap = redisTemplate.boundHashOps(redisKey);
        List<Object> values = couponMap.values();
        List<TCoupon> tCoupons = new ArrayList<>();
//        if(CollectionUtils.isNotEmpty(values)) {
//            if (tCoupon.getExpirationDate().compareTo(new Date())<0){
//                values.forEach(item->{
//                    String coupons = (String)item;
//                    TCoupon tCoupon1 = JSON.parseObject(coupons,TCoupon.class);
//                    tCoupons.add(tCoupon1);
//                });
//                return getDataTable(tCoupons);
//            }
//        }
        if (!values.isEmpty()){
            values.forEach(item->{
                System.out.println("=================================================>item.forEach执行");
                String coupons = (String) item;
                TCoupon tCoupon1 = JSON.parseObject(coupons, TCoupon.class);
                    //获取当前时间和过期时间
                    Date date = new Date(System.currentTimeMillis());
                    Date expirationDate = tCoupon1.getExpirationDate();
                    //判断过期时间是否已经到达当前时间后
                    if (expirationDate.after(date)){
                        //获取剩余时间
                        long time = expirationDate.getTime()-date.getTime();
                        if(time>0L){
                            tCoupons.add(tCoupon1);
                        } else {
                            couponMap.delete(tCoupon1.getCouponId()+"");
                        }
                    }else {
                        couponMap.delete(tCoupon1.getCouponId()+"");
                    }
            });
            return getDataTable(tCoupons);
        }
        List<TCoupon> list = tCouponService.selectTCouponList(tCoupon);
        for (TCoupon coupon : list) {
            Date date = new Date(System.currentTimeMillis());
            Date expirationDate = coupon.getExpirationDate();
            //判断过期时间是否已经到达当前时间后
            if (expirationDate.after(date)){
                //获取剩余时间
                long time = expirationDate.getTime()-date.getTime();
                if(time>0L){
                    //time/1000获得过期时间的秒数
                    couponMap.put(coupon.getCouponId()+"",JSON.toJSONString(coupon));
                }
            }
        }
        return getDataTable(list);
    }
//    @RequiresPermissions("marketing:coupon:list")
//    @GetMapping("/list")
//    public TableDataInfo list(TCoupon tCoupon)
//    {
//        String s = redisTemplate.opsForValue().get(redisKey);
//        TCoupon tCoupon1 = JSON.parseObject(s, TCoupon.class);
//        System.out.println(tCoupon1);
//        startPage();
//        List<TCoupon> list = tCouponService.selectTCouponList(tCoupon);
//        for (TCoupon coupon : list) {
//            String key=redisKey+coupon.getCouponId()+"";
////            获取当前时间和过期时间
//                    Date date = new Date(System.currentTimeMillis());
//                    Date expirationDate = coupon.getExpirationDate();
//                    //判断过期时间是否已经到达当前时间后
//                    if (expirationDate.after(date)){
//                        //获取剩余时间
//                        long time = expirationDate.getTime()-date.getTime();
//                        if(time>0L){
//                            //time/1000获得过期时间的秒数
//                            redisTemplate.opsForValue().set(key,JSON.toJSONString(coupon),time/1000,TimeUnit.SECONDS);
//                        }
//
//                    }
//        }
//        return getDataTable(list);
//    }



    /**
     * 导出优惠券管理列表
     */
    @RequiresPermissions("marketing:coupon:export")
    @Log(title = "优惠券管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCoupon tCoupon)
    {
        List<TCoupon> list = tCouponService.selectTCouponList(tCoupon);
        ExcelUtil<TCoupon> util = new ExcelUtil<TCoupon>(TCoupon.class);
        util.exportExcel(response, list, "优惠券管理数据");
    }

    /**
     * 获取优惠券管理详细信息
     */
    @RequiresPermissions("marketing:coupon:query")
    @GetMapping(value = "/{couponId}")
    public Result getInfo(@PathVariable("couponId") Integer couponId)
    {
        return success(tCouponService.selectTCouponByCouponId(couponId));
    }

    /**
     * 新增优惠券管理
     */
    @RequiresPermissions("marketing:coupon:add")
    @Log(title = "优惠券管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@RequestBody TCoupon tCoupon)
    {
        return toAjax(tCouponService.insertTCoupon(tCoupon));
    }

    /**
     * 修改优惠券管理
     */
    @RequiresPermissions("marketing:coupon:edit")
    @Log(title = "优惠券管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@RequestBody TCoupon tCoupon)
    {
        return toAjax(tCouponService.updateTCoupon(tCoupon));
    }

    /**
     * 删除优惠券管理
     */
    @RequiresPermissions("marketing:coupon:remove")
    @Log(title = "优惠券管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{couponIds}")
    public Result remove(@PathVariable Integer[] couponIds)
    {
        return toAjax(tCouponService.deleteTCouponByCouponIds(couponIds));
    }
}
